import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoSever {
    DatagramSocket socket = null;
    public UdpEchoSever(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //1 读取请求并解析
            DatagramPacket packet = new DatagramPacket(new byte[4096], 4096);
            socket.receive(packet);
            //执行完receive操作后，获取到的数据以字节型保存在packet中，要想显示并计算响应，需要将其转化为字符型
            String requese = new String(packet.getData(), 0, packet.getLength());
            //2 计算响应
            String respond = proccess(requese);
            //3 将计算的响应传回客户端
            //将响应数据构造进DatagramPacket对象中 这里使用字节型进行传输，汉字为3字节，英文为2字节
            //通过send传回客户端
            DatagramPacket back = new DatagramPacket(requese.getBytes(),
                    requese.getBytes().length, packet.getSocketAddress());
            socket.send(back);
            //printf格式化输出
            System.out.printf("[%s:%d] req=%s, resp=%s\n", back.getAddress().toString(), back.getPort(),
                    requese, respond);
        }
    }

    private String proccess(String requst) {
        return requst;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoSever udpEchoSever = new UdpEchoSever(9090);
        udpEchoSever.start();
    }
}
